<template>
  <div class="singer">
    <ul class="singer-header">
      <li v-for="(item,index) in harvestState" :key="index" @click="handleChangeView(item)"
          :class="{active:item.name==activeName}">
        {{item.name}}
      </li>
      <el-button type="primary" @click="centerDialogVisible = true">添加估产记录
      </el-button>
    </ul>
    <div>
      <content-list :contentList="data"></content-list>
      <div class="pagination">
        <el-pagination @current-change="handleCurrentChange" background layout="total,prev,pager,next"
                       :current-page="currentPage" :page-size="pageSize" :total="albumDatas.length">
        </el-pagination>
      </div>
    </div>
    <el-dialog title="添加估产记录" :visible.sync="centerDialogVisible" width="500px" center @close='closeDialog'>
      <el-form :model="registerForm" ref="registerForm" label-width="80px" :rules="rules">
        <el-form-item prop="username" label="上传识别" size="mini">
          <el-upload drag :action="uploadUrl()" :show-file-list="false" :on-success="handleAvatorSuccess"
                     :before-upload="beforeAvatorUpload" :limit="1"             :on-exceed="handleExceed"
                     :file-list="fileList"
                     list-type="picture">
            <i class="el-icon-upload"></i>
            <div>
              将文件拖到此处，或<span style="color:blue">点击此处上传</span>估产
            </div>
            <div slot="tip">只能上传jpg/png文件，且不能超过10MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item prop="location" label="图片面积" size="mini">
          <el-input v-model="registerForm.location" placeholder="图片的实际面积 "></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
                <el-button size="mini" @click="centerDialogVisible = false">取消</el-button>
                <el-button size="mini" @click="addConsumer">确定</el-button>
            </span>
    </el-dialog>

  </div>
</template>
<script>
  import ContentList from '../components/ContentList';
  import {selectHarvestByUser, getHarvestOfState} from '../api/index';
  import {mixin} from "../mixins";
  import {harvestState} from '../assets/data/harvestState';
  import {mapGetters} from 'vuex';

  export default {
    name: 'harvest',
    components: {
      ContentList
    },
    mixins: [mixin],
    data() {
      return {
        centerDialogVisible: false,
        albumDatas: [],      //记录数据
        pageSize: 15,        //页面大小，一页有15条数据
        currentPage: 1,      //当前页，默认第一页
        harvestState: [],           //全部状态
        activeName: '全部',   //当前状态
        registerForm: {      //添加框
          area: '',
          harvestId: '',
        },
        rules: {
          area: [
            {required: true, message: '请输入实际面积单位是平方米', trigger: 'blur'}
          ]
        },
        fileList: []
      }
    },
    computed: {
      //计算当前表格中的数据
      data() {
        return this.albumDatas.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
      },
      ...mapGetters([
        'listOfSongs',      //当前播放列表
        'userId',           //当前登录用户id
      ])
    },
    mounted() {
      this.harvestState = harvestState;
      this.getIdentifyList();
    },

    methods: {
      notify(title, type) {
        this.$notify({
          title: title,
          type: type
        })
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      handleRemove() {
      },
      closeDialog() {
        // this.$forceUpdate();
      },
      uploadUrl() {
        return `${this.$store.state.configure.HOST}/harvest/update_pic/${this.userId}`
      },
      //上传成功
      handleAvatorSuccess(res, file) {
        if (res.code === 200) {
          // this.reload();
          /*let tmp = this.$store.state.user.avator;
          console.log(tmp);
          this.$store.commit('setAvator','');
          this.$store.commit('setAvator',tmp);*/
          this.notify('修改成功', 'success');
        } else {
          this.notify('修改失败', 'error');
        }
      },
      //上传之前的校验
      beforeAvatorUpload(file) {
        const isJPG = file.type == 'image/jpeg';
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isJPG) {
          this.notify('上传头像图片只能是JPG格式', 'error');
          return false;
        }
        if (!isLt10M) {
          this.notify('上传头像图片不能大于10MB', 'error');
          return false;
        }
        return true;
      },
      //添加用户
      addConsumer() {
        this.$refs['registerForm'].validate(valid => {
          if (valid) {
            let d = this.registerForm.birth;
            let datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
            let params = new URLSearchParams();
            params.append('username', this.registerForm.username);
            params.append('password', this.registerForm.password);
            params.append('sex', this.registerForm.sex);
            params.append('phoneNum', this.registerForm.phoneNum);
            params.append('email', this.registerForm.email);
            params.append('birth', datetime);
            params.append('profession', this.registerForm.profession);
            params.append('location', this.registerForm.location);
            params.append('avator', '/img/user.jpg');
            addHarvest(params)
              .then(res => {
                if (res.code == 200) {
                  this.getData();
                  this.notify("添加成功", "success");
                } else {
                  this.notify("添加失败", "error");
                }
              })
              .catch(err => {
                console.log(err);
              });
            this.centerDialogVisible = false;
          }
        })
      },
      getIdentifyList() {
        selectHarvestByUser(this.userId)
          .then(res => {
            this.currentPage = 1;
            this.albumDatas = res.data;
          })
      },
      //获取当前页
      handleCurrentChange(val) {
        this.currentPage = val;
      },
      //todo 根据类型显示对应的记录
      handleChangeView(item) {
        this.activeName = item.name;
        this.albumDatas = [];
        if (item.name == '全部') {
          this.getIdentifyList();
        } else {
          this.getHarvestOfState(item.type)
        }
      },
      //todo 根据状态查询对应的记录
      getHarvestOfState(state) {
        getHarvestOfState(this.userId, state)
          .then(res => {
            this.currentPage = 1;
            this.albumDatas = res.data;
          })
      },

    }
  }
</script>

<style lang="scss" scoped>
  @import '../assets/css/singer.scss';
</style>
